package com.magist.manage.web.interceptor;


import com.magist.core.auth.AuthUser;
import com.magist.core.entity.CxtHolder;
import com.magist.core.entity.CxtRequest;
import com.magist.manage.web.dto.UserInfoDto;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class InitInterceptor implements HandlerInterceptor {

	private static org.slf4j.Logger logger = LoggerFactory.getLogger(InitInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 用户的放入
		Subject subject = SecurityUtils.getSubject();
		PrincipalCollection principals = subject.getPrincipals();
		if(ObjectUtils.isEmpty(principals)) {
			return true;
		}
		UserInfoDto userInfoDto =(UserInfoDto) principals.getPrimaryPrincipal();

		AuthUser user = new AuthUser();
		user.setUserId(userInfoDto.getId());
		user.setUserName(userInfoDto.getUserName());
		CxtRequest cxtR = new CxtRequest();
		cxtR.setRequestId(UUID.randomUUID().toString());
		cxtR.setUser(user);
		CxtHolder.setRequest(cxtR);

		return true;
	}

	/**
	 * 在业务处理器处理请求执行完成后,生成视图之前执行的动作 可在modelAndView中加入数据，比如当前时间
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	/**
	 * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
	 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion() 处理写session工作
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

}
